from PySide2.QtWidgets import QWidget, QPushButton, QFormLayout, QVBoxLayout, QHBoxLayout, QLineEdit, QComboBox, QMessageBox
from PySide2.QtCore import Signal

from tool import dbhelper, util, dbutil

class ConfigWidget(QWidget):

    callback_signal = Signal()

    def __init__(self):
        super(ConfigWidget, self).__init__()
        self.setupUi()

    def setupUi(self):
        self.layout = QVBoxLayout(self)

        self.formLayout = QFormLayout()
        self.layout.addLayout(self.formLayout)

        self.nameEdit = QLineEdit()
        self.nameEdit.setText(dbhelper.db_name)
        self.hostEdit = QLineEdit()
        self.hostEdit.setText(dbhelper.db_host)
        self.portEdit = QLineEdit()
        self.portEdit.setText(str(dbhelper.db_port))
        self.userEdit = QLineEdit()
        self.userEdit.setText(dbhelper.db_user)
        self.pwdEdit = QLineEdit()
        self.pwdEdit.setText(dbhelper.db_password)

        self.formLayout.addRow("数据库名称：", self.nameEdit)
        self.formLayout.addRow("数据库地址：", self.hostEdit)
        self.formLayout.addRow("数据库端口：", self.portEdit)
        self.formLayout.addRow("用户名：", self.userEdit)
        self.formLayout.addRow("密码", self.pwdEdit)

        self.button = QPushButton("确定")
        self.button.setMaximumWidth(300)
        self.button.clicked.connect(self.onClick)
        self.buttonLayout = QHBoxLayout()

        self.buttonLayout.addWidget(self.button)
        self.layout.addLayout(self.buttonLayout)
        self.layout.addStretch(1)

    def onClick(self):
        name = self.nameEdit.text()
        host = self.hostEdit.text()
        port = self.portEdit.text()
        user = self.userEdit.text()
        pwd = self.pwdEdit.text()

        if len(name) == 0 or len(host) == 0 or len(port) == 0 or len(user) == 0 or len(pwd) == 0:
            QMessageBox.warning(self, '', "请正确填写数据库配置", QMessageBox.Yes)
            return

        result = QMessageBox.information(
            self, '相关配置', "确定配置", QMessageBox.No | QMessageBox.Yes)
        
        if result == QMessageBox.Yes:
            dic = {
                "name": name,
                "host": host,
                "port": port,
                "user": user,
                "pwd": pwd,
            }
            util.set_main_config(dic)

            # 验证数据库连接是否成功
            succes = dbutil.main()
            if succes == False:
                QMessageBox.warning(self, '', "数据库配置错误", QMessageBox.Yes)
                return

            self.callback_signal.emit()
            self.close()

        

